/**
 * Thinking in java 
 *  2018/08/01
 */
package com.dzb.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;


/**
 * @author dzb
 * @date 2018年8月15日 下午5:38:31
 * @description  
 * @version 1.0.0
 */
public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

	
	private  AsynchronousSocketChannel  channel;
	
	
	/**
	 * 
	 */
	public ReadCompletionHandler(AsynchronousSocketChannel channel) {
		if(this.channel==null){
			this.channel=channel;
		}
	}

	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		
		try {
			attachment.flip();//接收附件
			byte[] body = new byte[attachment.remaining()];
			attachment.get(body);
			String req =new String(body, "UTF-8");
			System.out.println("接收客户端发送的数据:"+new String(req));
			if(req==null){
				req=System.currentTimeMillis()+"";
			}
			doWrite(req);//写入附件
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}

	
	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		  try {
			this.channel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		  
	}

	
	public void doWrite(String currenttime){
		 if(currenttime!=null&&currenttime.trim().length()>0){
			 byte[] bytes = currenttime.getBytes();
			 ByteBuffer writebuffer = ByteBuffer.allocate(1024);
			 writebuffer.put(bytes);
			 writebuffer.flip();
			 channel.write(writebuffer, writebuffer, new CompletionHandler<Integer, ByteBuffer>() {
				@Override
				public void completed(Integer result, ByteBuffer attachment) {
					//如果没有完成 则继续发送
					if(attachment.hasRemaining()){
						channel.read(attachment, attachment, this);
					}
				}

				@Override
				public void failed(Throwable exc, ByteBuffer attachment) {
					try {
						channel.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			});
		 }
	}
	
}
